0
\$\begingroup\$

As part of the bigger problem I am trying to solve smaller problems first and hence below is the code to find the terminal width and height.

Code

'use strict';
class Terminal {
 width() {
 return process.stdout.columns || 80
 }
 height() {
 return process.stdout.rows || 60
 }
}
module.exports = Terminal

How can I make the above code testable? can I use some better abstraction?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jun 30, 2017 at 4:29
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

What is the functionality of this class? Get width and height from process.stdout, an external resource, or else fall back to default values.

You can make this testable by making it possible to inject process.stdout, the external resource. Then in the test you can inject an object that you control, and verify that Terminal uses that object correctly or else falls back to the defaults correctly.

To make process.stdout injectable, you have at least two options:

  • Add an optional constructor argument. By default use process.stdout, only the test method will inject a custom object.
  • Add a _stdout function, that will be used by width and height, and in the test override it appropriately.
answered Jun 30, 2017 at 14:51
\$\endgroup\$
2
  • \$\begingroup\$ First alternative seems better to me. Also, what could be the name of the injected argument? \$\endgroup\$ Commented Jun 30, 2017 at 16:17
  • \$\begingroup\$ @CodeYogi I would call it simply stdout \$\endgroup\$ Commented Jun 30, 2017 at 17:01

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.